package org.jetlinks.pro.clickhouse.types;

import lombok.AllArgsConstructor;
import lombok.Generated;
import lombok.Getter;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.jetlinks.pro.clickhouse.ClickHouseDataType;

import java.sql.JDBCType;
import java.sql.SQLType;
import java.util.ArrayList;

@AllArgsConstructor(staticName = "of")
public class ArrayDataType implements ClickHouseDataType {

    @Getter
    private final ClickHouseDataType elementType;

    @Override
    @Generated
    public String getId() {
        return "Array";
    }

    @Override
    @Generated
    public String getName() {
        return "Array";
    }

    @Override
    @Generated
    public SQLType getSqlType() {
        return JDBCType.ARRAY;
    }

    @Override
    @Generated
    public Class<?> getJavaType() {
        return ArrayList.class;
    }

    @Override
    public String createColumnDataType(RDBColumnMetadata columnMetaData) {

        return "Array(" + elementType.createColumnDataType(columnMetaData) + ")";
    }

    public static class Parser implements DataTypeParser {

        @Override
        public boolean support(String expr) {
            return expr.startsWith("Array(");
        }

        @Override
        public ClickHouseDataType parse(String expr) {
            String ele = expr.substring(6, expr.length() - 1);
            ClickHouseDataType eleType = ClickHouseDataTypes
                .parse(ele)
                .orElseThrow(() -> new UnsupportedOperationException("不支持的类型:" + ele));
            return ArrayDataType.of(eleType);
        }
    }
}
